package com.dmtt.web.service.impl;

import com.dmtt.web.common.CheckCode;
import com.dmtt.web.entity.*;
import com.dmtt.web.mapper.CarStatusMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.Socket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CarStatusServiceImpl {

    @Autowired
    private CarStatusMapper carStatusMapper;

    @Autowired
    private CheckCode checkCode;

//    @Override
//    public void point() {
//        List<CarStatus> map = carStatusMapper.findStatus();
//        for (CarStatus carStatus : map) {
//            if (carStatus.getJobId() == -1){
//                System.out.println(carStatus.getAgvName());
//            }
//        }
//        System.out.println(map);
//    }

    //日期转时间戳
    public long timeNum(String time) throws ParseException {
        Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);
        Long time1 = parse.getTime();
        return time1;
    }

    //老车实时获取小车状态
    public void oldCar(){
        try {
            Calendar calendar=Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startTime = formatter.format(calendar.getTime());
            String agvName = "#%";
            List<OldPoint> oldPoints = carStatusMapper.oldCar(agvName);
            for (OldPoint oldPoint : oldPoints) {
                AgvSaveStatus agvSaveStatus = carStatusMapper.currStatus(oldPoint.getAgvName());
                String jobName = null;
                if (oldPoint.getJobName() != null) {
                    jobName = "%" + oldPoint.getJobName() + "%";
                }
                if (agvSaveStatus == null){
                    OldPoint oldPoint1 = new OldPoint();
                    oldPoint1.setAgvStatus(3);
                    oldPoint1.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                    oldPoint1.setAgvName(oldPoint.getAgvName());
                    oldPoint1.setPoint(oldPoint.getPoint());
                    oldPoint1.setStartTime(startTime);
                    carStatusMapper.saveOld(oldPoint1);
                }else {
                    if (timeNum(agvSaveStatus.getStartTime())<timeNum(startTime)) {
                        OldPoint oldPoint1 = new OldPoint();
                        PointInfo pointInfo = carStatusMapper.pointInfo(oldPoint.getPoint(),jobName);
                        //待机
                        if(pointInfo != null) {
                            if (oldPoint.getJobId() == -1 && oldPoint.getAgvStatus() == 0 && pointInfo.getOrigin() == 1 && agvSaveStatus.getStatus() != 2) {
                                carStatusMapper.updateStatus(startTime, agvSaveStatus.getAgvId(), oldPoint.getPoint(),oldPoint.getJobName());
                                oldPoint1.setAgvStatus(2);
                                oldPoint1.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                                oldPoint1.setAgvName(oldPoint.getAgvName());
                                oldPoint1.setPoint(oldPoint.getPoint());
                                oldPoint1.setStartTime(startTime);
                                carStatusMapper.saveOld(oldPoint1);
                            }
                        }
                        //有任务并且agv表中状态为0
                        if (oldPoint.getAgvStatus() == 0) {
                            //交通管制
                            if (oldPoint.getMuxzone() != -1 && agvSaveStatus.getStatus() != 5) {
                                carStatusMapper.updateStatus(startTime, agvSaveStatus.getAgvId(),oldPoint.getPoint(),oldPoint.getJobName());
                                oldPoint1.setAgvStatus(5);
                                oldPoint1.setStartTime(startTime);
                                oldPoint1.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                                oldPoint1.setAgvName(oldPoint.getAgvName());
                                oldPoint1.setPoint(oldPoint.getPoint());
                                carStatusMapper.saveOld(oldPoint1);
                            }else if (pointInfo != null){
                                if (agvSaveStatus.getPoint() != oldPoint.getPoint()) {
                                    //上下货空箱满箱
                                    //上下货 空箱
                                    loadAndUnload(oldPoint.getPoint(), oldPoint.getAgvName(), pointInfo, agvSaveStatus.getStatus(), oldPoint.getJobName());
                                }
                            }
                        }
                        if(oldPoint.getAgvStatus() != 0 && agvSaveStatus.getStatus() != oldPoint.getAgvStatus()){
                            //异常
                            carStatusMapper.updateStatus(startTime, agvSaveStatus.getAgvId(),oldPoint.getPoint(),oldPoint.getJobName());
                            oldPoint1.setPoint(oldPoint.getPoint());
                            oldPoint1.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                            oldPoint1.setAgvStatus(oldPoint.getAgvStatus());
                            oldPoint1.setStartTime(startTime);
                            oldPoint1.setAgvName(oldPoint.getAgvName());
                            //保存新的AGV状态
                            carStatusMapper.saveOld(oldPoint1);
                        }
//                        else if(agvSaveStatus.getStatus() != 0){
//                            //原点异常
//                            carStatusMapper.updateStatus(startTime, agvSaveStatus.getAgvId(),oldPoint.getPoint(),oldPoint.getJobName());
//                            oldPoint1.setPoint(oldPoint.getPoint());
//                            oldPoint1.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
//                            oldPoint1.setAgvStatus(oldPoint.getAgvStatus());
//                            oldPoint1.setStartTime(startTime);
//                            oldPoint1.setAgvName(oldPoint.getAgvName());
//                            //保存新的AGV状态
//                            carStatusMapper.saveOld(oldPoint1);
//                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    //老车状态判断
    public void olsStatus(OldPoint oldPoint,String startTime){
        OldPoint oldPoint1 = new OldPoint();
        oldPoint1.setAgvStatus(3);
        oldPoint1.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
        oldPoint1.setAgvName(oldPoint.getAgvName());
        oldPoint1.setPoint(oldPoint.getPoint());
        oldPoint1.setStartTime(startTime);
        carStatusMapper.saveOld(oldPoint1);
    }


    //查询新车的AGVName和agvIP
    public void findAgv(){
        //查询小车的ID和IP
        int i = 0;
        List<AgvList> agvLists = carStatusMapper.agvList("$%");
        for (AgvList agvList : agvLists) {
            socketAgv(agvList,i);
        }
    }

    //新车socket连接获取返回值
    private void socketAgv(AgvList agvList, int flag){
        Socket socket = null;
        String[] str = new String[26];
        InputStream is = null;
        try {
            String start;
            socket = new Socket(agvList.getAgvIp(),8899);
//            System.out.println("connection...");
            if (agvList.getAgvId().length() == 2) {
                start = "55 0" + agvList.getAgvId().charAt(1) + " " + randomHexString() + " 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00";
            } else {
                start = "55 " + agvList.getAgvId().substring(1,3) + " " + randomHexString() + " 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00";
            }
            String start1 = checkCode.checkCode(start);
            //得到socket读写流,向服务端程序发送数据
            socket.getOutputStream().write(start1.getBytes());
//            System.out.println("发送消息:"+start1);
            byte[] datas = new byte[26];
            //从服务端程序接收数据
            is = socket.getInputStream();
            int i = 0;
            do {
                i++;
                is.read(datas);
            }while (is.available() != 0 || i==3);
            if (i==3){
                socket.close();
                return;
            }

//            for (int i = 0; i < 3; i++) {
//                if (i == 2) {
//                    if (is.available() == 0) {
//                        return;
//                    }
//                }
//            }
//            is.read(datas);
            str = bytesToString(datas);
//            System.out.println("接收消息："+Arrays.toString(str));
            flag++;
            if (str[25].equals("00")){
                if (flag < 2) {
                    socketAgv(agvList, flag);
                } else {
                    socket.close();
                    return;
                }
            } else {
                statusSave(str,agvList.getJobName());
            }
            socket.close();
        }catch (Exception e){
            try {
                statusSave1(4,agvList.getAgvId(),agvList.getJobName());
            } catch (Exception exception){
                exception.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    //新车关机数据库存储
    private void statusSave1(int agvStatus,String agvName,String jobName) throws ParseException {
        AgvSaveStatus agvSaveStatus =  new AgvSaveStatus();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String startTime = simpleDateFormat.format(date);
        //查询agv_temp表中当前车的最新状态
        AgvSaveStatus status = carStatusMapper.currStatus(agvName);
        if (status == null){
            OldPoint oldPoint1 = new OldPoint();
            oldPoint1.setAgvStatus(3);
            oldPoint1.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
            oldPoint1.setAgvName(agvName);
            oldPoint1.setStartTime(startTime);
            carStatusMapper.saveOld(oldPoint1);
        }
        if (timeNum(startTime)>timeNum(status.getStartTime())) {
            if (status.getStatus() != agvStatus) {
                //修改AGV表中的异常信息
                carStatusMapper.updateAgvStatus(agvStatus, agvName);
                //修改agv_temp表中的状态和结束时间
                carStatusMapper.updateStatus(startTime, status.getAgvId(),status.getPoint(),jobName);
                agvSaveStatus.setPoint(status.getPoint());
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStatus(agvStatus);
                agvSaveStatus.setStartTime(startTime);
                agvSaveStatus.setAgvName(agvName);
                //保存新的AGV状态
                carStatusMapper.save(agvSaveStatus);
            }
        }
    }

    //数据库存储逻辑
    private void statusSave(String[] str,String jobName) throws ParseException {
        AgvSaveStatus agvSaveStatus =  new AgvSaveStatus();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String startTime = simpleDateFormat.format(date);
        Integer agvStatus = 0;
        int a = Integer.parseInt(str[5],16);
        if (a != 4){
            agvStatus = statusBetter(a);
        }
        String stringBuffer = "";
        stringBuffer = stringBuffer + (str[7]);
        stringBuffer = stringBuffer + (str[6]);
        String stringBuffer1 = "";
        String electric = "";
        for (int i = 0;i<4;i++){
            if (!stringBuffer.substring(i,i+1).equals("0")){
                stringBuffer1 = stringBuffer1 + (stringBuffer.substring(i,i+1));
            }
        }
        for (int i = 0;i<str[22].length();i++){
            if (str[22].charAt(i) != '0'){
                electric = electric + (str[22].charAt(i));
            }
        }
        String agvName = str[1].charAt(0) == '0' ?str[1].substring(1,2):str[1];
        agvName = "$" +agvName;
        //交通管制1.查询新车交通管制状态
        OldPoint traffic = carStatusMapper.traffic(agvName);
        if (traffic.getMuxzone() != -1){
            agvStatus = 5;
        }
        //修改AGV表里的站点
        if (stringBuffer1 != null && stringBuffer1 != "") {
            carStatusMapper.updateAgvPoint(Integer.parseInt(stringBuffer1, 16), agvName);
        }
        //查询agv_temp表中当前车的最新状态
        AgvSaveStatus status = carStatusMapper.currStatus(agvName);
        if (status == null){
            OldPoint oldPoint1 = new OldPoint();
            oldPoint1.setAgvStatus(3);
            oldPoint1.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
            oldPoint1.setAgvName(agvName);
            oldPoint1.setStartTime(startTime);
            carStatusMapper.saveOld(oldPoint1);
            return ;
        }
        String point = stringBuffer1;
        //修改电量
        int a1 = 0;
        if (electric != "") {
            a1 = Integer.parseInt(electric, 16);
        }
        if (a1 != 255 && a1 != 0){
            carStatusMapper.updateElectric(a1, agvName);
        }
        //判断状态为待机，修改数据库为完成状态，job表添加任务完成时间
//        if (agvStatus == 2){
//            long flag = carStatusMapper.findJobId(agvName);
//            carStatusMapper.updateJobStatus(agvName,-1);
//            carStatusMapper.updateJobTime(flag,startTime,3);
//        }
        int p = -1;
        if (point != "") {
            p = Integer.parseInt(point, 16);
        }
        if (timeNum(startTime)>timeNum(status.getStartTime())) {
            if (agvStatus == 2 || agvStatus == 0) {
                PointInfo pointInfo = carStatusMapper.pointInfo(p,"%"+jobName+"%");
                if (pointInfo != null) {
                    loadAndUnload1(p, agvName, pointInfo, agvStatus, jobName);
                } else if(!status.getStatus().equals(agvStatus)) {
                    //修改AGV表中的异常信息
                    carStatusMapper.updateAgvStatus(agvStatus, agvName);
                    //修改agv_temp表中的状态和结束时间
                    carStatusMapper.updateStatus(startTime, status.getAgvId(),p,jobName);
                    agvSaveStatus.setPoint(p);
                    agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                    agvSaveStatus.setStatus(agvStatus);
                    agvSaveStatus.setStartTime(startTime);
                    agvSaveStatus.setAgvName(agvName);
                    //保存新的AGV状态
                    carStatusMapper.save(agvSaveStatus);
                }
            } else if (!status.getStatus().equals(agvStatus)) {
                //修改AGV表中的异常信息
                carStatusMapper.updateAgvStatus(agvStatus, agvName);
                //修改agv_temp表中的状态和结束时间
                carStatusMapper.updateStatus(startTime, status.getAgvId(),p,jobName);
                agvSaveStatus.setPoint(p);
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStatus(agvStatus);
                agvSaveStatus.setStartTime(startTime);
                agvSaveStatus.setAgvName(agvName);
                //保存新的AGV状态
                carStatusMapper.save(agvSaveStatus);
            }
        }
    }

    private Integer statusBetter(Integer status) {
        Integer result = 0;
        switch (status) {
            case 0:
                return 2;
            case 1:
                return 0;
            case 2:
                return 17;
            case 3:
                return 14;
            case 4:
                return 16;
            case 5:
                return 23;
            case 6:
                return 15;
            case 7:
                return 24;
            case 8:
                return 1;
            case 9:
                return 25;
            case 10:
                return 26;
            case 11:
                return 27;
            case 12:
                return 28;
        }
        return result;
    }

    //随机生成两位16进制数
    public String randomHexString()  {
        try {
            int len =4;
            StringBuffer result = new StringBuffer();
            for(int i=0;i<len;i++) {
                result.append(Integer.toHexString(new Random().nextInt(16)));
                if (i==1){
                    result.append(" ");
                }
            }
            return result.toString().toUpperCase();

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }
        return null;
    }

    //存储调试
    public void agvStatusUpdate(String endTime) {
        carStatusMapper.deleteStatisticeTemp();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH,0);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String startTime = simpleDateFormat.format(calendar.getTime()) + " 00:00:00";
        List<OldPoint> list = carStatusMapper.agvStatus();
        for (OldPoint oldPoint : list) {
            AgvSaveStatus agvSaveStatus = carStatusMapper.currStatus(oldPoint.getAgvName());
            if (agvSaveStatus != null) {
                carStatusMapper.updateStatus(endTime, agvSaveStatus.getAgvId(), oldPoint.getPoint(), oldPoint.getJobName());
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStatus(3);
                agvSaveStatus.setStartTime(startTime);
                agvSaveStatus.setPoint(oldPoint.getPoint());
                carStatusMapper.save(agvSaveStatus);
                carStatusMapper.updateAgvStatus(3, oldPoint.getAgvName());
            }
        }
    }

    //字节数组转16进制字符串
    public String[] bytesToString(byte[] bytes){
        String hexStr = "0123456789ABCDEF";
        String[] result = new String[bytes.length];
        String hex = "";
        int i = 0;
        for (byte b : bytes) {
            hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
            hex += String.valueOf(hexStr.charAt(b & 0x0F));
            result[i] = hex;
            i++;
        }
        return result;
    }

    //agv正常行驶 判断agv到原点修改状态为待机，   到上下货站点为上下货，空箱满箱
    public int loadAndUnload(Integer point,String agvName,PointInfo pointInfo,Integer agvStatus,String jobName){
        try {
            AgvSaveStatus agvSaveStatus = new AgvSaveStatus();
            //查询agv_temp表中当前车的最新状态
            AgvSaveStatus status = carStatusMapper.currStatus(agvName);
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            String startTime = simpleDateFormat.format(date);
            calendar.add(Calendar.SECOND, pointInfo.getStopTime());
            String endTime = simpleDateFormat.format(calendar.getTime());
            //空箱和下货等待
            if (pointInfo.getOrigin() == 3 && agvStatus != 7) {
                //下货
                carStatusMapper.updateStatus(startTime, status.getAgvId(),point,jobName);
                agvSaveStatus.setPoint(point);
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStatus(7);
                agvSaveStatus.setStartTime(startTime);
                agvSaveStatus.setEndTime(endTime);
                agvSaveStatus.setAgvName(agvName);
                //保存新的AGV状态
                carStatusMapper.save(agvSaveStatus);
                //空箱
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStatus(6);
                agvSaveStatus.setStartTime(endTime);
                agvSaveStatus.setAgvName(agvName);
                //保存新的AGV状态
                carStatusMapper.save(agvSaveStatus);
                return 1;
            }
            //上货
            else if (pointInfo.getOrigin() == 2 && agvStatus != 7) {
                carStatusMapper.updateStatus(startTime, status.getAgvId(),point,jobName);
                agvSaveStatus.setPoint(point);
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStatus(7);
                agvSaveStatus.setStartTime(startTime);
                agvSaveStatus.setEndTime(endTime);
                agvSaveStatus.setAgvName(agvName);
                //保存新的AGV状态
                carStatusMapper.save(agvSaveStatus);
                //满箱状态开始
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStartTime(endTime);
                agvSaveStatus.setEndTime(null);
                agvSaveStatus.setStatus(0);
                carStatusMapper.save(agvSaveStatus);
                return 1;
            }
            //原点空箱
            else if (pointInfo.getOrigin() == 1 && agvStatus != 6) {
                carStatusMapper.updateStatus(startTime, status.getAgvId(),point,jobName);
                agvSaveStatus.setPoint(point);
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStatus(6);
                agvSaveStatus.setStartTime(endTime);
                agvSaveStatus.setAgvName(agvName);
                //保存新的AGV状态
                carStatusMapper.save(agvSaveStatus);
                return 1;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    public int loadAndUnload1(Integer point,String agvName,PointInfo pointInfo,Integer agvStatus,String jobName){
        try {
            AgvSaveStatus agvSaveStatus = new AgvSaveStatus();
            //查询agv_temp表中当前车的最新状态
            AgvSaveStatus status = carStatusMapper.currStatus(agvName);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            String startTime = simpleDateFormat.format(date);
            //下货等待
            if (pointInfo.getOrigin() == 3 && agvStatus != 2) {
                //修改AGV表中的异常信息
                carStatusMapper.updateAgvStatus(7, agvName);
                //下货
                carStatusMapper.updateStatus(startTime, status.getAgvId(),point,jobName);
                agvSaveStatus.setPoint(point);
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStatus(7);
                agvSaveStatus.setStartTime(startTime);
                agvSaveStatus.setAgvName(agvName);
                //保存新的AGV状态
                carStatusMapper.save(agvSaveStatus);
                return 7;
            }
            //空箱
            else if (pointInfo.getOrigin() == 3 && agvStatus == 0) {
                //修改AGV表中的异常信息
                carStatusMapper.updateAgvStatus(0, agvName);
                carStatusMapper.updateStatus(startTime, status.getAgvId(),point,jobName);
                agvSaveStatus.setPoint(point);
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStatus(6);
                agvSaveStatus.setStartTime(startTime);
                agvSaveStatus.setAgvName(agvName);
                //保存新的AGV状态
                carStatusMapper.save(agvSaveStatus);
                return 6;
            }
            //上货
            else if (pointInfo.getOrigin() == 2 && agvStatus != 2) {
                //修改AGV表中的异常信息
                carStatusMapper.updateAgvStatus(7, agvName);
                carStatusMapper.updateStatus(startTime, status.getAgvId(),point,jobName);
                agvSaveStatus.setPoint(point);
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStatus(7);
                agvSaveStatus.setStartTime(startTime);
                agvSaveStatus.setAgvName(agvName);
                //保存新的AGV状态
                carStatusMapper.save(agvSaveStatus);
                return 7;
            }
            //满箱
            else if (pointInfo.getOrigin() == 2 && agvStatus == 0) {
                //修改AGV表中的异常信息
                carStatusMapper.updateAgvStatus(0, agvName);
                carStatusMapper.updateStatus(startTime, status.getAgvId(),point,jobName);
                agvSaveStatus.setPoint(point);
                agvSaveStatus.setAgvName(agvName);
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStartTime(startTime);
                agvSaveStatus.setStatus(0);
                carStatusMapper.save(agvSaveStatus);
                return 0;
            }
            //原点空箱
            else if (pointInfo.getOrigin() == 1 && agvStatus != 6) {
                //修改AGV表中的异常信息
                carStatusMapper.updateAgvStatus(6, agvName);
                carStatusMapper.updateStatus(startTime, status.getAgvId(),point,jobName);
                agvSaveStatus.setPoint(point);
                agvSaveStatus.setAgvId(UUID.randomUUID().toString().replaceAll("-", ""));
                agvSaveStatus.setStatus(6);
                agvSaveStatus.setStartTime(startTime);
                agvSaveStatus.setAgvName(agvName);
                //保存新的AGV状态
                carStatusMapper.save(agvSaveStatus);
                return 6;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

}
